package com.nxmu.hire.service.impl;

import com.nxmu.hire.common.exception.ServiceException;
import com.nxmu.hire.dao.UserMapper;
import com.nxmu.hire.model.User;
import com.nxmu.hire.model.UserExample;
import com.nxmu.hire.service.UserService;
import com.nxmu.hire.vo.LoginReqVo;
import com.nxmu.hire.vo.ModifyPasswordReqVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    private final static Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据用户名和密码获取用户列表
     *
     * @param loginReqVo
     * @return
     */
    @Override
    public List<User> getUserByUserIdAndPassword(LoginReqVo loginReqVo) {
        User user = new User();
        BeanUtils.copyProperties(loginReqVo,user);
        UserExample userExample = new UserExample();

        userExample.createCriteria()
                .andUserIdEqualTo(user.getUserId())
                .andPasswordEqualTo(user.getPassword())
                .andRoleEqualTo(user.getRole());
        return userMapper.selectByExample(userExample);
    }

    /**
     * 修改密码
     * @param modifyPasswordReqVo
     * @throws ServiceException
     */
    @Transactional
    @Override
    public void modifyPassword(ModifyPasswordReqVo modifyPasswordReqVo) throws ServiceException {
        if (!Objects.equals(modifyPasswordReqVo.getPassword(),modifyPasswordReqVo.getConformPassword())) throw new ServiceException("密码不一致");

        User user = userMapper.selectByPrimaryKey(modifyPasswordReqVo.getUserId());

        if (!Objects.equals(modifyPasswordReqVo.getOldPassword(),user.getPassword())) throw new ServiceException("旧密码错误");

        user.setPassword(modifyPasswordReqVo.getPassword());
        try {
            userMapper.updateByPrimaryKey(user);
        } catch (Exception e) {
            LOGGER.error("密码更新失败");
            throw new ServiceException("修改密码失败！");
        }
    }

    /**
     * 根据id查询用户
     * @param userId
     * @return
     */
    @Override
    public User findUserByUserId(String userId) {
        return userMapper.selectByPrimaryKey(userId);
    }
}
